home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10148 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  68 lines

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Determining the length of an int in string form
  5. Date: Fri, 15 Mar 96 16:21:16 GMT
  6. Organization: none
  7. Message-ID: <826906876snz@genesis.demon.co.uk>
  8. References: <3146D058.DD7@cbm.com> <3147BE0D.296@hsc.unt.edu>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <3147BE0D.296@hsc.unt.edu>
  15.            sfogoros@hsc.unt.edu "Steve Fogoros" writes:
  16.  
  17. >Dave Payne wrote:
  18. >> 
  19. >> Consider this:
  20. >> 
  21. >> I have a variable of type int, and I would like to use the sprintf()
  22. >> function to write this variable to a string.  However, I want to
  23. >> dynamically allocate the space for the string, and only malloc enough
  24. >> space to hold the int.  Here's a code fragment that may illustrate this
  25. >> more clearly:
  26. >> 
  27. >
  28. >Here is what I would do,
  29. >
  30. > char buf[80]; // int could be any length when converted. (Twenty years from
  31. > now
  32. >               //    will int be 256 bits? That would be over 80 digits.)
  33. >               // In the mean time you should make buf at least buf[12] because
  34. >               //    int could be 32 bits. For 64 bit use buf[22];
  35.  
  36. If you are writng C code you can't use // - it is a syntax error.
  37.  
  38. There is no need to make buf an external declaration - it can be a local
  39. variable in func1().
  40.  
  41. You can calculate a suitable size for buf e.g.
  42.  
  43. #include <limits.h>
  44.  
  45. #define INTBUF_SIZE    (sizeof(int) * CHAR_BIT / 3 + 2)
  46.  
  47. > void func1()  {
  48. >   int    i = 1234;
  49. >   char  *a;
  50. >   sprintf(buf,"%s%d","The value of i is ",i);
  51.  
  52. And with the reduced buffer size we'd better make that:
  53.  
  54.     sprintf(buf,"%d",i);
  55.  
  56. >   a = malloc(strlen(buf + 1));
  57.  
  58. Don't forget that sprintf returns the length of the string it writes, unless
  59. your system library is prehistoric.
  60.  
  61. -- 
  62. -----------------------------------------
  63. Lawrence Kirby | fred@genesis.demon.co.uk
  64. Wilts, England | 70734.126@compuserve.com
  65. -----------------------------------------
  66.